package com.edoovo.loginservice.application.controller;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.edoovo.loginservice.application.config.auth.CustomUserDetailsService;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.Objects;

/**
 * 通用登录认证
 *
 */
@RestController
@RequestMapping("/public")
@RequiredArgsConstructor
public class CommonController {

	@Autowired
	private CustomUserDetailsService customUserDetailsService;

	/**
	 * 用户登录成功返回token
	 * 或者是用户token 刷新
	 * @param name
	 * @return
	 */
	@GetMapping("/token")
	public String getToken(String name, String password) {

		//获取登录用的信息
		UserDetails userDetails = customUserDetailsService.loadUserByUsername(name);

		Map<String, Object> paramMap = Maps.newHashMap();
		paramMap.put("username", "test@edoovo.com");//明文
		paramMap.put("password", "12345678");//明文
		paramMap.put("permission", userDetails.getAuthorities()); //添加用户权限

		//用户密码验证
		String response = HttpUtil.post("http://localhost:8080/oauth/token", paramMap);
		Map<String, Object> tokenMap = JSONUtil.toBean(response, new TypeReference<Map<String, Object>>() {}, true);
		if (Objects.nonNull(tokenMap)) {
			return "Bearer " + tokenMap.get("access_token");
		}
		return "Get token fail";
	}

	/**
	 * token 过期刷新
	 * @param name
	 * @return
	 */
	@GetMapping("/refresh-token")
	public String getToken(String name) {

		//获取登录用的信息
		UserDetails userDetails = customUserDetailsService.loadUserByUsername(name);

		Map<String, Object> paramMap = Maps.newHashMap();
		paramMap.put("username", "test@edoovo.com");//明文
		paramMap.put("password", userDetails.getPassword());
		paramMap.put("permission", userDetails.getAuthorities()); //添加用户权限

		//用户密码验证
		String response = HttpUtil.post("http://localhost:8080/oauth/token", paramMap);
		Map<String, Object> tokenMap = JSONUtil.toBean(response, new TypeReference<Map<String, Object>>() {}, true);
		if (Objects.nonNull(tokenMap)) {
			return "Bearer " + tokenMap.get("access_token");
		}
		return "Get token fail";
	}

}